<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>

    class EventBus {
      constructor() {
        this.eventObject = {}

      }
      //函数的最后一个命名参数以...为前缀，则它将成为一个由剩余参数组成的真数组
      $emit(eventName, ...args) {
        if (!this.eventObject[eventName]) {
          return console.warn(eventName + '不存在')
        }
        const callbackList = this.eventObject[eventName];
        for (let fn of callbackList) {
          fn(...args)
        }
      }
      $on(eventName, callback) {
        if (!this.eventObject[eventName]) {
          this.eventObject[eventName] = []
        }
        this.eventObject[eventName].push(callback)
      }
      /* 
        不传参数，删除全部，
        
      */
      $off(event, callback) {
        if (!arguments.length) {
          this.eventObject = {}
        }
        if (!this.eventObject[event]) {
          return console.warn('事件不存在')
        }
        if (this.eventObject[event].length == 1) {
          delete this.eventObject[event];
          return;
        }
        for (let i = 0; i < this.eventObject[event].length; i++) {
          let cb = this.eventObject[event][i];
          if (cb == callback) {
            this.eventObject[event].splice(i, 1);
            break;
          }
        }


      }

      $once(event, fn) {
        let _this = this;
        function hanlder(...args) {
          fn.apply(_this, args);
          _this.$off(event)
        }
        this.$on(event, hanlder)
      }
    }

    const event1 = new EventBus()
    event1.$on('create', (row) => {
      console.log(row, '1')
    })
    event1.$on('create', (row) => {
      console.log(row, '2')
    })
    const fn = (row) => {
      console.log(row, '3')
    }
    event1.$once('create', fn)
    event1.$emit('create', { name: 1, age: 2 }, 1, 2, 3)
    // event1.$off('create', fn)
    event1.$emit('create', { name: 3, age: 2 })
  </script>
</body>

</html>